package ru.niir.goodfil.excel.impl;

import org.apache.poi.ss.usermodel.Cell;
import ru.niir.goodfil.audit.util.Assert;
import ru.niir.goodfil.excel.client.CellRenderer;
import ru.niir.goodfil.excel.client.ColumnModel;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author: Кирилл
 */
public class DateCellRenderer implements CellRenderer {
    private final SimpleDateFormat sdf;
    private final boolean nullable;

    public DateCellRenderer(String dateFormatPattern) {
        Assert.notBlank(dateFormatPattern);

        this.sdf = new SimpleDateFormat(dateFormatPattern);
        this.nullable = true;
    }

    public DateCellRenderer(String dateFormatPattern, boolean nullable) {
        Assert.notBlank(dateFormatPattern);

        this.sdf = new SimpleDateFormat(dateFormatPattern);
        this.nullable = nullable;
    }

    public void render(Cell cell, Object object, ColumnModel columnModel) {
        Assert.notNull(cell);
        Assert.notNull(columnModel);

        if (object == null) {
            if (!nullable) {
                throw new IllegalArgumentException();
            } else {
                return;
            }
        }

        Assert.notNull(object);
        Assert.isInstanceOf(object, java.util.Date.class,
                java.sql.Date.class,
                java.sql.Timestamp.class,
                java.util.Calendar.class,
                java.util.GregorianCalendar.class);

        if (java.util.Date.class.isInstance(object)) {
            java.util.Date d = (Date) object;
            Assert.notNull(d);

            cell.setCellValue(sdf.format(d));
            return;
        }
        if (java.sql.Date.class.isInstance(object)) {
            java.sql.Date d = (java.sql.Date) object;
            Assert.notNull(d);

            cell.setCellValue(sdf.format(d));
            return;
        }
        if (java.sql.Timestamp.class.isInstance(object)) {
            java.sql.Timestamp d = (Timestamp) object;
            Assert.notNull(d);

            cell.setCellValue(sdf.format(d));
            return;
        }
        if (java.util.Calendar.class.isInstance(object)) {
            java.util.Calendar d = (Calendar) object;
            Assert.notNull(d);

            cell.setCellValue(sdf.format(d.getTime()));
            return;
        }

        Assert.exception();
    }
}
